package com.ruoyi.bytetopdance;

import com.alibaba.fastjson.JSON;
import com.ruoyi.bytetopdance.domain.CommonResponse;
import com.ruoyi.bytetopdance.domain.ImageTransRequest;
import com.ruoyi.bytetopdance.domain.ImageTransResponse;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.exception.ByteDanceCallException;
import com.ruoyi.util.CertSign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.Random;

/**
 * https://bytedance.feishu.cn/docx/CHrKdjZhFoeU6uxXNGOc20XDn2f
 *
 * @author chenchuan2
 * @date 2023-01-16 14:00:13
 */
@Component
@Slf4j
public class ByteDanceImageTransClient {

    private static final String URL = "https://cv-api.bytedance.com/api/common/v2/process?api_key={0}&timestamp={1}&nonce={2}&sign={3}";

    private static final String apiKey = "26c33f8d957711ed9e003e2f64c82880";

    private static final String securityKey = "26c372c4957711ed9e003e2f64c82880";

    @Autowired
    private RestTemplate restTemplate;

    public ImageTransResponse transImage(String url) {
        String requestId = "";
        try {
            //设置签名
            String nonce = String.format("%d", Math.abs(new Random().nextInt()));
            String timestamp = Long.toString(System.currentTimeMillis() / 1000);
            String sign = CertSign.genCertSign(nonce, timestamp, securityKey);
            String queryUrl = MessageFormat.format(URL, apiKey, timestamp, nonce, sign);
            ImageTransRequest request = new ImageTransRequest();
            request.setImage_url(url);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(request), headers);

            //执行请求
            ResponseEntity<CommonResponse<ImageTransResponse>> exchange = restTemplate.exchange(
                    queryUrl,
                    HttpMethod.POST,
                    formEntity,
                    new ParameterizedTypeReference<CommonResponse<ImageTransResponse>>() {
                    }); // 解决 CommonResult 的泛型丢失
            CommonResponse<ImageTransResponse> result = exchange.getBody();
            requestId = result.getRequest_id();
            if (!StringUtils.equals(result.getCode().toString(), "10000")) {
                throw new ByteDanceCallException(result.getMessage(), requestId);
            }
            ImageTransResponse data = result.getData();
            data.setRequestId(requestId);
            return data;
        } catch (Exception ex) {
            log.error("byteDance transImage error[{}]", url, ex);
            throw new ByteDanceCallException(ex.getMessage(), requestId);
        }
    }
}
